<?php

namespace App\Http\Controllers;

use App\Code;
use Illuminate\Http\Request;
use App\User;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    private $answer;
    //
    public function reg( Code $code)
    {

        $code = $code->getRand();
        return view('login.reg',compact('code'));
    }

    public function store(Request $request,User $user)
    {
        if(session('answer') != $request->vercode)
        {
            return ['error'=>1,'info'=>'验证码错误'];
        }
        $this->validate($request,[
            'name'=>'max:20|min:3',
            'email'=> 'unique:users|email',
            'password'=> 'max:20|min:3|confirmed',
        ]);
        $user->name = $request->name;
        $user->password = bcrypt($request->password);
        $user->email = $request->email;
        $user->save();
        return  ['error' => 0 , 'info' => '注册成功'];
    }
    public function login(Code $code)
    {
        $code = $code->getRand();
        return view('login.login',compact('code'));
    }
    public function loginStore()
    {
        if(session('answer') != request()->vercode)
        {
            return ['error'=>1,'info'=>'验证码错误'];
        }
        $this->validate(request(),[
            'email'=> 'required|email',
            'password'=> 'max:20|min:3',
        ]);
        $user = request(['email','password']);
        if(\Auth::attempt($user)){
            return ['error'=>0,'info'=>'登陆成功'];
        }

        return ['error'=>1,'info'=>'用户名或密码错误'];
    }
    public function logout()
    {
        \Auth::logout();
        return redirect('/login');
    }

    public function adminLogin()
    {
        return view("admin.login.login");
    }
    public function adminLoginStore()
    {
        $this->validate(request(),[
            'name'=> 'required|min:3',
            'password'=> 'max:20|min:3',
        ]);
        $admin = request(['name','password']);
        if(\Auth::guard('admin')->attempt($admin)){
            return ['error'=>0,'info'=>'登陆成功'];
        }
        return ['error'=>1,'info'=>'用户名或密码错误'];
    }
    public function adminLogout()
    {
        \Auth::guard('admin')->logout();
        return redirect('admin/login');
    }
}
